<?php
namespace app\small\controller;
use app\common\base\_Db;
use app\common\base\curl;
use think\Controller;
use think\Db;

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/1/18
 * Time: 14:46
 */
class Index extends Controller {
    /*
     * 用户使用授权
     */
    public function index(){
        $code = input('code');
        $encryptedData = input('encryptedData');
        $iv = urldecode(input("iv"));
        $Appid = small_config()['Appid'];
        $Secret = small_config()['Secret'];
        $wx_token_url='https://api.weixin.qq.com/sns/jscode2session?appid='.$Appid.'&secret='.$Secret.'&js_code='.$code.'&grant_type=authorization_code';
        $wx_return=curl::http_curl($wx_token_url);
        $arr = json_decode($wx_return,true);
        //$arr包含openID和session_key
        $sessionKey = $arr['session_key'];
        $openid = $arr['openid'];
        $errCode =Auth::decryptData($encryptedData, $iv, $data, $sessionKey);
        $userInfo=json_decode($data,true);
        $where = 'openid = "'.$openid.'"';
        $user_result = _Db::GetData('user',array('user_id'=>'uid','iden'=>'iden'),$where.'and iden = 1');
        //用户表为空
        if (empty($user_result)){
            $staff_result = _Db::GetData('staff',array('staff_id'=>'uid','regist'=>'regist'),$where);
            //系统员工表为空
            if (empty($staff_result)){
                $external_result = _Db::GetData('external_staff',array('id'=>'uid','regist'=>'regist'),$where);
                //驻场职工表为空
                if (empty($external_result)){
                    //获取用户信息存入用户表
                    $param_field = [
                        'openid'     => $userInfo['openId'],
                        'nick_name'  => $userInfo['nickName'],
                        'avatar_url' => $userInfo['avatarUrl'],
                        'gender'     => $userInfo['gender'],
                        'country'    => $userInfo['country'],
                        'province'   => $userInfo['province'],
                        'city'       => $userInfo['city'],
                        'language'   => $userInfo['language'],
                        //'status'   => 1,//用户状态
                    ];
                    $user_where = 'openid = "'.$param_field['openid'].'"';
                    if (_Db::GetData('user',array('user_id'=>'uid','iden'=>'iden'),$user_where)){
                        Db::name('user')->where($user_where)->delete();
                    }
                    Db::table('user')->insert($param_field);
                    $userId = Db::name('user')->getLastInsID();
                    $res = array(
                        'uid' => $userId,
                        'iden'=> 1
                    );
                }elseif ($external_result['regist'] == 3){
                    $res['uid'] = $external_result['uid'];
                    $res['iden'] = 3;
                    $res['status'] = 'success';
                }else{
                    $res['uid'] = $external_result['uid'];
                    $res['iden'] = 3;
                }
            }elseif ($staff_result['regist'] == 3){
                $res['uid'] = $staff_result['uid'];
                $res['iden'] = 2;
                $res['status'] = 'success';
            }else{
                $res['uid'] = $staff_result['uid'];
                $res['iden'] = 2;
            }
        }else{
            $res['uid'] = $user_result['uid'];
            $res['iden'] = 1;
        }
        if ($errCode == 0) {
            return json_encode($res);
        } else {
            return $errCode;
        }
    }
    /*
     * 二次访问
     */
    public function Verif(){
        $uid = input('uid');
        $iden = input('iden');//身份
        $res= Db::table('user')->field('user_id as uid,iden,openid')->where('user_id = '.$uid)->find();
        if ($iden == 1){
            //旅客
            $result['uid'] = $res['uid'];
            $result['iden'] = $res['iden'];
        }elseif ($iden == 2){
            //机场职工
            $table_name='staff';
            $field = array('staff_id'=>'uid','regist'=>'regist','openid'=>'openid');
            if (empty($res)){
                //uid非user表id
                $res_staff = _Db::GetData($table_name,$field,'staff_id = '.$uid);
            }else{
                $res_staff = _Db::GetData($table_name,$field,'openid = "'.$res['openid'].'"');
            }
            if ($res_staff['regist'] == 3){
                $result['uid'] = $res_staff['uid'];
                $result['iden'] = 2;
                $result['status'] = 'success';
            }elseif ($res_staff['regist'] == 4){
                $res_user = _Db::GetData('user','user_id as uid,iden,openid','openid = "'.$res_staff['openid'].'"');
                $result['uid'] = $res_user['uid'];
                $result['iden'] = 2;
            } else{
                $result['uid'] = $uid;
                $result['iden'] = $iden;
            }
        } elseif ($iden == 3){
            //驻场职工
            $table_name='external_staff';
            $field = array('id'=>'uid','regist'=>'regist','openid'=>'openid');
            if (empty($res)){
                $res_exter = _Db::GetData($table_name,$field,'id = '.$uid);
            }else{
                $res_exter = _Db::GetData($table_name,$field,'openid = "'.$res['openid'].'"');
            }
            if ($res_exter['regist'] == 3){
                $result['uid'] = $res_exter['uid'];
                $result['iden'] = 3;
                $result['status'] = 'success';
            }elseif ($res_exter['regist'] == 4){
                $res_user = _Db::GetData('user','user_id as uid,iden,openid','openid = "'.$res_exter['openid'].'"');
                $result['uid'] = $res_user['uid'];
                $result['iden'] = 3;
            }else{
                $result['uid'] = $uid;
                $result['iden'] = $iden;
            }
        }
        return json_encode($result);
    }
    /*
     * 职工注册
     * 短信验证（暂无）
     * 小程序提交，默认regist= 1（未注册）后台审核
     */
    public function Regist(){
        $uid = input('uid');
        $iden = input('zIden');//身份  0:机场职工,1:驻场职工
        $name = input('zName');//姓名
        $phone = input('zPhone');//电话
        $key = input('zKey');//秘钥
        $result = Db::table('user')
            ->field('user_id as uid,iden,openid')
            ->where('user_id = "'.$uid.'"')
            ->find();
        $openid = $result['openid'];
        $field = array(
            'openid'=>$openid,
            'regist'=>2
        );
        $res = array();
        //通过姓名、电话、及四位秘钥
        $where = 'phone_number = "'.$phone.'" and nick_name = "'.$name.'"';
        if ($iden == 0){
            $table_name='staff';
            $info = Db::table($table_name)->where($where)->find();
            $id = $info['staff_id'];
            $res ['iden'] = 2;
        }elseif ($iden == 1){
            $table_name='external_staff';
            $info = Db::table($table_name)->where($where)->find();
            $id = $info['id'];
            $res ['iden'] = 3;
        }
        if ($info){
            if ($info['regist'] == 1){
                //未申请
                if (Db::table($table_name)->where($where)->update($field)){
                    //申请成功
                    $res ['state'] = 1;
                    return json_encode($res);
                }
            }elseif ($info['regist'] == 2){
                //已申请
                $res ['state'] = 2;
                return json_encode($res);
            }elseif ($info['regist'] == 3){
                //已审核
                $res ['uid'] = $id;
                $res ['state'] = 3;
                $res ['status'] = 'success';
                return json_encode($res);
            }elseif ($info['regist'] == 4){
                //已驳回 regist=4
                $res ['iden'] = 1;
                $res ['state'] = 4;
                return json_encode($res);
            }
        }else{
            //查无此人
            $res ['iden'] = 1;
            $res ['state'] = 0;
            return json_encode($res);
        }
    }
}